/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { GLFrame } = require("../../engine/GLFrame");
const { DAEObject } = require("../../engine/graphics/DAEObject");
const { X3DFast, X2DBeta } = require("../../engine/graphics/X2DInterface");
const { XMat4 } = require("../../engine/graphics/XMat4");
const { Scr } = require("../../engine/XDefine");
const { XTools } = require("../../engine/XTools");
const { AttributeArea } = require("../AttributeArea");
const { LogManager } = require("../ros1/LogManager");
const { CreateCustomPart } = require("./CreateCustomPart");
const { EditRobot } = require("./EditRobot");
const { SaveRobotConfig } = require("./SaveRobotConfig");
const { SelectRobotPart } = require("./SelectRobotPart");

class RobotManager {
    static getInstance() {
        if (!RobotManager.instance) {
            RobotManager.instance = new RobotManager();
        }
        return RobotManager.instance;
    }
    constructor() {
        this.tmat = new XMat4();
        this.robots = [
            this.robotTemplate("robot1")
        ];
        this.status = "main";
        this.editingRobotPoint = -1;
        this.editingRobotPoint = 0;
        this.selectPart = SelectRobotPart.getInstance();
        this.editRobot = EditRobot.getInstance();

        // this.reset("main", true);
        SaveRobotConfig.getInstance().loadConfig(() => {
            if (this.robots.length > 0) {
                this.editRobot.init(this.robots[0]);
            }
            this.editRobot.open();
            // CreateCustomPart.reset();
            // CreateCustomPart.updateAttributeArea();
        });

        // this.editRobot.init(this.robots[0]);
        // {//todo remove default
        //     this.editRobot.addPart("body", "xMdStWrrg6pZbPe5");
        //     this.editRobot.addPart("left_arm", "fq1fF952rhf0l7SM");
        //     this.editRobot.addPart("right_arm", "fq1fF952rhf0l7SM");
        //     this.editRobot.robot.parts[0].isRoot = true;
        //     this.editRobot.robot.parts[1].parent = "body_1";
        //     this.editRobot.robot.parts[1].xyz.x = -1;
        //     this.editRobot.robot.parts[2].parent = "body_1";
        //     this.editRobot.robot.parts[2].xyz.x = 1;
        //     this.editRobot.open();
        // }
    }
    robotTemplate(name) {
        return {
            name: name,
            parts: [],//部件（可见实体）
            joints: [],//关节（连接各部件）
        }
    }
    reset(stat = "main", focus = false) {
        if (!focus && this.status === stat) {
            return;
        }
        this.status = stat;
        CreateCustomPart.on = false;
        AttributeArea.gi().clear();
        switch (this.status) {
            case "main":
                AttributeArea.gi().addTitle("自定义仿真机器人");
                AttributeArea.gi().addGap(1);

                let names = [];
                for (let r of this.robots) {
                    names.push(r.name);
                }
                AttributeArea.gi().addList({
                    label: `已有机器人列表(${this.robots.length})：`,
                    list: names,
                    default: this.editingRobotPoint >= 0 ? this.robots[this.editingRobotPoint].name : "",
                    height: 100,
                    callback: (value) => {
                        for (let r of this.robots) {
                            if (r.name === value) {
                                this.editingRobotPoint = this.robots.indexOf(r);
                                this.editRobot.init(r);
                                this.reset("main", true);
                                return;
                            }
                        }
                    }
                });
                if (this.editingRobotPoint >= 0) {
                    AttributeArea.gi().addGap(1);
                    AttributeArea.gi().addButton({
                        label: "编辑" + this.robots[this.editingRobotPoint].name,
                        callback: () => {
                            this.editRobot.open();
                        },
                    });
                    AttributeArea.gi().addGap(1);
                    AttributeArea.gi().addButton({
                        label: "删除" + this.robots[this.editingRobotPoint].name,
                        callback: () => {
                            this.robots.splice(this.editingRobotPoint, 1);
                            this.editingRobotPoint = -1;
                            this.reset("main", true);
                            SaveRobotConfig.getInstance().saveConfig();
                        },
                    });
                }

                AttributeArea.gi().addGap(1);
                AttributeArea.gi().addButton({
                    label: "创建新的仿真机器人",
                    callback: () => {
                        this.tmpCreateRobot = this.robotTemplate("new_robot");
                        this.reset("add_new_robot");
                    },
                });
                break;
            case "add_new_robot":
                AttributeArea.gi().addTitle("创建新的仿真机器人");
                AttributeArea.gi().addGap(1);
                AttributeArea.gi().addInput({
                    label: "机器人名称：",
                    default: this.tmpCreateRobot.name,
                    callback: (value) => {
                        this.tmpCreateRobot.name = value;
                    },
                });
                AttributeArea.gi().addGap(1);
                AttributeArea.gi().addButton({
                    label: "确定创建",
                    callback: () => {
                        let name = this.tmpCreateRobot.name.trim();
                        if (name === "") {
                            LogManager.E("机器人名称不能为空！");
                            return;
                        }
                        for (let r of this.robots) {
                            if (r.name === name) {
                                LogManager.E(`机器人名称${name}已存在，请重新输入！`);
                                return;
                            }
                        }
                        this.tmpCreateRobot.name = name;
                        this.robots.push(this.tmpCreateRobot);
                        this.reset();
                        SaveRobotConfig.getInstance().saveConfig();
                    },
                });
                break;
        }
        AttributeArea.gi().flush();
    }

    onDraw() {
        if (CreateCustomPart.on) {
            CreateCustomPart.onDraw();
            return;
        }

        if (this.editRobot.on) {
            this.editRobot.onDraw();
        }
        if (this.selectPart.on) {
            this.selectPart.onDraw();
        }
    }

    onTouch(msg, x, y) {
        if (CreateCustomPart.on) {
            if (CreateCustomPart.onTouch(msg, x, y)) {
                return true;
            }
            return true;
        }
        if (this.selectPart.on) {
            this.selectPart.onTouch(msg, x, y);
            switch (this.selectPart.operate) {
                case "create_custom_part"://新建部件
                    CreateCustomPart.reset();
                    CreateCustomPart.updateAttributeArea();
                    break;
                case "edit_custom_part"://编辑已有部件
                    CreateCustomPart.reset(this.selectPart.selectedPart);
                    CreateCustomPart.updateAttributeArea();
                    break;
                case "add_to_robot"://部件添加到机器人
                    this.editRobot.addPart(this.selectPart.selectedPart.name, this.selectPart.selectedPart.token);
                    break;
            }
            return true;
        }
        if (this.editRobot.on) {
            this.editRobot.onTouch(msg, x, y);
            return true;
        }
        return true;
    }
}

module.exports = {
    RobotManager
};